package VLSys;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Component;
import javax.swing.table.DefaultTableModel;

import DBConnection.*;
import java.sql.*;

import VLSObjects.*;

public class ManagementServiceEdit extends JPanel{
    
    JTextField serviceName;
    IntegerField serviceAmount;
    JTextField serviceID;
    JComboBox serviceForSize;
    JComboBox serviceAvailablity;
    String[] sizeChoices = { "", "Small", "Medium","Large"};
    String[] availablityChoices = { "", "Available", "Unavailable"};
    JButton submitButton;
    JButton cancelButton;
    JButton getButton;
    JButton editServiceButton;
    JLabel serviceNameLabel;
    JLabel serviceSizeLabel;
    JLabel serviceAmountLabel;
    JLabel serviceAvailabilityLabel;
    JLabel editServiceLabel;
    JLabel serviceIDLabel;
    
    JTextField filter;
    JLabel filterLabel;
    
    JScrollPane serviceScroll;
    JTable serviceTable;
    /*
    ImageIcon ask = new ImageIcon("images/prompt_ask.png");
    ImageIcon notice = new ImageIcon("images/prompt_notice.png");
    */
    
    ImageIcon notice_green = new ImageIcon("images/prompt_notice_green.png");
    ImageIcon ask_red = new ImageIcon("images/prompt_ask_red.png");
    ImageIcon notice_red = new ImageIcon("images/prompt_notice_red.png");
    
    DefaultTableModel modelTransactions;
    
    int enable = 1;
    int x = -1;
    
    Object headers[] = {"ServiceID", "Service Name", "Size", "Amount", "Available"};

    String blank = "";
    String string[] = new String[5];
    
    public ManagementServiceEdit(final JFrame frame)
    {
        setVisible(false);
        setLayout(null);
        setBackground(null);
        
        serviceID = new JTextField();
        serviceName = new JTextField();
        serviceAmount = new IntegerField();
        serviceForSize = new JComboBox(sizeChoices);
        serviceAvailablity = new JComboBox(availablityChoices);
                
        serviceIDLabel = new JLabel("ServiceID:");
        serviceNameLabel = new JLabel("Service:");
        serviceSizeLabel = new JLabel("Size:");
        serviceAmountLabel = new JLabel("Amount:");
        serviceAvailabilityLabel = new JLabel("Available:");
        editServiceLabel = new JLabel("EDIT SERVICE");
        
        getButton = new JButton();
        submitButton = new JButton();
        cancelButton = new JButton();
        editServiceButton = new JButton();
        
        editServiceLabel.setFont(new Font("sansserif", Font.PLAIN, 40));
        editServiceLabel.setBounds(10,10,300,30);
        serviceIDLabel.setBounds(65,50,150,20);
        serviceNameLabel.setBounds(73,75,150,20);
        serviceSizeLabel.setBounds(92,100,150,20);
        serviceAmountLabel.setBounds(72,125,150,20);
        serviceAvailabilityLabel.setBounds(65,150,150,20);
        
        serviceID.setBounds(130,50,200,20);        
        serviceName.setBounds(130,75,200,20);
        serviceForSize.setBounds(130,100,200,20);
        serviceAmount.setBounds(130,125,200,20);
        serviceAvailablity.setBounds(130,150,200,20);
        
        serviceID.setBorder(null);
        serviceName.setBorder(null);
        serviceForSize.setBorder(null);
        serviceAmount.setBorder(null);
        serviceAvailablity.setBorder(null);
        
        
        submitButton.setText("Submit");
        cancelButton.setText("Clear");
        editServiceButton.setText("Edit"); 
        
       
        submitButton.setBounds(175,175,75,20);
        cancelButton.setBounds(255,175,75,20);
        editServiceButton.setBounds(15, 390, 75, 20);
        
        filterLabel = new JLabel("Search:");
        filterLabel.setBounds(394,390,150,20);
        
        filter = new JTextField();
        filter.setBounds(439,390,150,20);
        filter.setBorder(null);
        
        //table codes
        
        serviceTable = new JTable();
        serviceTable.setModel(new javax.swing.table.DefaultTableModel(null, headers) {

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        }
        );
        
        modelTransactions = (DefaultTableModel)serviceTable.getModel();
    
        serviceScroll = new JScrollPane();
        serviceTable.getTableHeader().setReorderingAllowed(false);
        
                
        serviceScroll.setViewportView(serviceTable);
        serviceScroll.setBounds(15, 240, 575, 150);
        serviceTable.getTableHeader().setResizingAllowed(false);
        
        disableButton();
        populateTable("SELECT * FROM servicelist");
         
        add(serviceID);
        add(serviceName);
        add(serviceForSize);
        add(serviceAmount);
        add(serviceAvailablity);
        add(submitButton);
        add(cancelButton);
        add(editServiceButton);
        add(serviceIDLabel);
        add(serviceNameLabel);
        add(serviceSizeLabel);
        add(serviceAmountLabel);
        add(serviceAvailabilityLabel);
        add(editServiceLabel);
        add(serviceScroll);
        add(filter);
        add(filterLabel);
        
        filter.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent e) {
              
              if (e.getKeyCode()==39 || e.getKeyCode()==37)
        {
               
        }
              else 
                filter.setText(capitalizeFirstLetters(filter.getText()));
     
          

          populateTable("SELECT * FROM servicelist WHERE serviceName LIKE '" + filter.getText() + "%' ORDER BY serviceName ASC");
          
          }

          public void keyTyped(KeyEvent e) {
          }

          public void keyPressed(KeyEvent e) {
          }
        });
        
        serviceTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMouseClicked(evt);
            }
        }
        );
        
        editServiceButton.addActionListener(new  ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if(x != -1)
                    enableButton();
                else
                    JOptionPane.showMessageDialog(frame,
                                "Please Select Service",
                                "Vehicle Logging Service",
                                JOptionPane.WARNING_MESSAGE,
                                notice_red);
            }
        }
        ); 
        
        serviceName.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode()==39 || e.getKeyCode()==37)
                {

                }
                else 
                    serviceName.setText(capitalizeFirstLetters(serviceName.getText())); 
          }

          public void keyTyped(KeyEvent e) {
              
          }

          public void keyPressed(KeyEvent e) {
              
          }
        }
        );
        
        submitButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                               
                string[0] = serviceName.getText();
                string[1] = (String)serviceForSize.getSelectedItem();
                string[2] = serviceAmount.getText();
                string[3] = (String)serviceAvailablity.getSelectedItem();

                if(string[0].length() == 0 && string[1] == blank && string[2].length() == 0 && string[3] == blank)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                    
                } 
                else if(string[0].length()== 0 || string[1] == blank || string[2].equals(blank) || string[3] == blank)
                {
                    checkEmpty();
                    
                        if(string[0].length() > 25)
                        {
                            checkEmpty();
                            JOptionPane.showMessageDialog(frame,
                                        "Invalid and Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                        }    
                        else if(string[0].length() == 0 || string[1] == blank || string[2].equals(blank) || string[3] == blank )
                            JOptionPane.showMessageDialog(frame,
                                        "Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);                     
                }   
                else if(string[0].length() > 25)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Invalid Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                }            
                else if(string[0].length() <= 25 && string[1] != blank && string[2] != blank)   
                {
                    int n = JOptionPane.showConfirmDialog(frame,
                                        "Proceed with current values?",
                                        "Vehicle Logging Service",
                                        JOptionPane.YES_NO_OPTION,
                                        JOptionPane.QUESTION_MESSAGE,
                                        ask_red);
                    if(n==0)
                    {
                        Service editService = new Service();
                        ServiceManager newSm = new ServiceManager();

                        editService.setServiceID(serviceID.getText());
                        editService.setServiceName(string[0]);
                        
                        editService.setSize(string[1]);
                        
                        editService.setAmount(Integer.parseInt(string[2]));
                        
                        if(string[3].equals("Available") == true)
                            editService.setAvailable("Yes");
                        if(string[3].equals("Unavailable") == true)
                            editService.setAvailable("No");
                        
                      boolean existing = newSm.checkService(string[0], string[1], serviceID.getText());
                       //check if a similar record already exists
                           
                       if(existing == true) 
                           {    JOptionPane.showMessageDialog(frame,
                                            "Service record already exists!",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                           }
                           else
                           {   //add to database if no similar record is found
                               
                                boolean result = newSm.editService(editService);
                                if (result == true)
                                    JOptionPane.showMessageDialog(frame,
                                                "Service Edit!",
                                                "Vehicle Logging Service",
                                                JOptionPane.WARNING_MESSAGE,
                                                notice_green);
                                resetValues();
                                x=-1;
                          }
                       
                        modelTransactions.setRowCount(0); 
                        disableButton();
                        
                        populateTable("SELECT * FROM servicelist");
                    }
                }
            }
        }
        );
        
        cancelButton.addActionListener(new  ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                int n = JOptionPane.showConfirmDialog(
                                    frame,
                                    "Are you sure you want to clear the values?",
                                    "Vehicle Logging Service",
                                    JOptionPane.YES_NO_OPTION,
                                    JOptionPane.QUESTION_MESSAGE,
                                    ask_red);
               if(n==0)
                { 
                resetValues();
                disableButton();
                x=-1;
                }   
            }
        }
        );
    }
    
    public void checkEmpty()
    {   
        String s = "";
       
        if(serviceName.getText().length() == 0)
            serviceName.setBackground(Color.YELLOW);
               
        else if(serviceName.getText().length() > 25)
            serviceName.setBackground(Color.RED);
        
        else if(serviceName.getText().length() <= 25)
            serviceName.setBackground(null);
        
        if((String)serviceForSize.getSelectedItem() == s)
            serviceForSize.setBackground(Color.YELLOW);
        
        if((String)serviceForSize.getSelectedItem() != s)
            serviceForSize.setBackground(null);
        
        if( serviceAmount.getText().length() == 0)
            serviceAmount.setBackground(Color.YELLOW);
        
        if( serviceAmount.getText().length() != 0)
            serviceAmount.setBackground(null);
        
        if((String)serviceAvailablity.getSelectedItem() == s)
            serviceAvailablity.setBackground(Color.YELLOW);
        
                
        if((String)serviceAvailablity.getSelectedItem() != s)
            serviceAvailablity.setBackground(null);
    }
    
    public void disableButton()
    {
        serviceID.setEnabled(false);
        serviceID.setEditable(false);
        serviceName.setEnabled(false);
        serviceAmount.setEnabled(false);
        serviceForSize.setEnabled(false);
        serviceAvailablity.setEnabled(false);
        cancelButton.setEnabled(false);
        submitButton.setEnabled(false);
        editServiceButton.setEnabled(true);
        
        enable = 1;
    }
    
    public void enableButton()
    {
        serviceName.setEnabled(true);
        serviceAmount.setEnabled(true);
        serviceForSize.setEnabled(true);
        serviceAvailablity.setEnabled(true);
        submitButton.setEnabled(true);
        cancelButton.setEnabled(true);
        editServiceButton.setEnabled(false);
        enable = 0;
    }
    
    public void resetValues()
    {
        serviceName.setBackground(null);
        serviceForSize.setBackground(null);
        serviceAmount.setBackground(null);
        serviceAvailablity.setBackground(null);

        disableButton();

        serviceName.setText("");
        serviceForSize.setSelectedItem("");
        serviceAmount.setText("");
        serviceAvailablity.setSelectedItem("");
        
        x = -1;
    }
    
    private void TableMouseClicked(java.awt.event.MouseEvent evt) 
   {                                     
       int rowSelected = serviceTable.getSelectedRow();
       if(enable == 1)
       {
           x = rowSelected;
           int sID = (Integer)modelTransactions.getValueAt(x, 0);
           int sAmount = (Integer)modelTransactions.getValueAt(x, 3);
           
       
            serviceID.setText(Integer.toString(sID));
            serviceName.setText((String)modelTransactions.getValueAt(x, 1));

            serviceForSize.setSelectedItem(modelTransactions.getValueAt(x, 2));

            serviceAmount.setText((Integer.toString(sAmount)));         

            if(modelTransactions.getValueAt(x, 4).equals("Yes") == true )
                serviceAvailablity.setSelectedItem("Available");

            if(modelTransactions.getValueAt(x, 4).equals("No") == true)
                serviceAvailablity.setSelectedItem("Unavailable");
       }
    }
    
    public void populateTable(String pS){
         
              try{
                    //opens db connection
                    ConnectionFactory myFactory = ConnectionFactory.getFactory();
                    Connection conn = myFactory.getConnection();

                    //SQL Query
                    PreparedStatement pstmt = conn.prepareStatement(pS);

                    //execute query
                    ResultSet rs = pstmt.executeQuery();
                    
                    modelTransactions.getDataVector().removeAllElements();
                    serviceTable.setAutoCreateRowSorter(true);
                    

                    //populate JTable 
                    while(rs.next()){
                    modelTransactions.addRow(new Object[]{rs.getInt(1), rs.getString(2), rs.getString(3),rs.getInt(4), rs.getString(5)});
                    modelTransactions.fireTableDataChanged();
                    }

                    //close DB connection
                    conn.close();
                }
                      
                catch(SQLException e)
                {
                   e.printStackTrace();
                   System.out.print("ayaw!");
                }
          }
    
    public static String capitalizeFirstLetters ( String s ) {

        for (int i = 0; i < s.length(); i++) {

            if (i == 0) {
                // Capitalize the first letter of the string.
                s = String.format( "%s%s",
                             Character.toUpperCase(s.charAt(0)),
                             s.substring(1) );
            }

            // Is this character a non-letter or non-digit?  If so
            // then this is probably a word boundary so let's capitalize
            // the next character in the sequence.
            if (!Character.isLetterOrDigit(s.charAt(i))) {
                if (i + 1 < s.length()) {
                    s = String.format( "%s%s%s",
                                 s.subSequence(0, i+1),
                                 Character.toUpperCase(s.charAt(i + 1)),
                                 s.substring(i+2) );
                }
            }

        }
        return s;

    }
}
